package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.AdminService;
import com.longkier.gx_library_springboot.entity.Admin;
import com.longkier.gx_library_springboot.entity.BookAdmin;
import com.longkier.gx_library_springboot.exception.CustomException;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/adminManage/")
@RequiredArgsConstructor
public class AdminController {
    private final AdminService adminService;
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    // 系统管理员部分

    /**
     * 创建一个新的系统管理员。
     *
     * @param admin 包含新管理员详细信息的 Admin 对象
     * @return 包含创建结果的响应对象
     * @throws CustomException 如果用户名已存在或发生其他异常
     */
    @PostMapping("/admins/create")
    public Map<String, Object> creatAdmin(@RequestBody Admin admin) {
        try {
            if (adminService.admin_UsernameTaken(admin.getUsername())) {
                throw new CustomException(403, "用户名已存在");
            } else {
                return RequestUtils.buildResponse(adminService.createAdmin(admin), 200);
            }
        } catch (CustomException e) {
            logger.error("注册用户时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 批量删除系统管理员。
     *
     * @param params 请求体，包含 adminIds 列表
     * @return 删除结果的响应对象
     * @throws CustomException 如果请求参数中缺少 adminIds 或删除失败
     */
    @DeleteMapping("/admins/batch/delete")
    public Map<String, Object> batchDeleteAdmins(@RequestBody Map<String, Object> params) {
        try {
            if (!params.containsKey("adminIds")) {
                throw new CustomException(400, "请求参数中缺少 adminIds");
            }
            List<Long> adminIds = RequestUtils.processIds(params.get("adminIds"));
            boolean success = adminService.batchDeleteAdmins(adminIds);

            if (success) {
                return RequestUtils.buildResponse("删除成功", 200);
            } else {
                throw new CustomException(500, "部分或全部用户删除失败");
            }
        } catch (IllegalArgumentException e) {
            throw new CustomException(400, e.getMessage());
        } catch (Exception e) {
            logger.error("删除用户时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "删除用户时发生异常：" + e.getMessage());
        }
    }

    /**
     * 获取系统管理员列表。
     *
     * @param request 请求体，包含分页信息（page, size）和过滤条件（status, username, adminName）
     * @return 包含管理员列表的响应对象
     * @throws CustomException 如果发生异常
     */
    @PostMapping("/admins/all")
    public Map<String, Object> getAdmins(@RequestBody Map<String, Object> request) {
        try {
            int page = (int) request.getOrDefault("page", 0);
            int size = (int) request.getOrDefault("size", 10);
            Integer status = (Integer) request.get("status");
            String username = (String) request.get("username");
            String adminName = (String) request.get("adminName");
            Page<Admin> admins = adminService.getAllAdmins(page, size, status, username, adminName);
            return RequestUtils.buildResponse(admins, 200);
        } catch (Exception e) {
            logger.error("获取管理员列表时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "服务器内部错误");
        }
    }

    /**
     * 更新指定 ID 的系统管理员信息。
     *
     * @param id           管理员的 ID
     * @param adminDetails 包含更新信息的 Admin 对象
     * @return 包含更新结果的响应对象
     * @throws CustomException 如果发生异常
     */
    @PutMapping("/admins/update/{id}")
    public Map<String, Object> updateAdmin(@PathVariable Long id, @RequestBody Admin adminDetails) {
        try {
            Optional<Admin> updatedAdmin = adminService.updateAdminService(id, adminDetails);
            return RequestUtils.buildResponse(updatedAdmin, 200);
        } catch (Exception e) {
            logger.error("更新管理员时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "服务器内部错误");
        }
    }

    /**
     * 批量更新系统管理员的状态。
     *
     * @param request 请求体，包含 adminIds 列表和 status
     * @return 更新状态结果的响应对象
     * @throws CustomException 如果请求参数中缺少 adminIds 或 status，或更新失败
     */
    @PutMapping("/admins/batch/status")
    public Map<String, Object> batchUpdateAdminStatus(@RequestBody Map<String, Object> request) {
        try {
            List<Long> adminIds = RequestUtils.processIds(request.get("adminIds"));
            Integer status = (Integer) request.get("status");
            boolean success = adminService.batchUpdateAdminStatus(adminIds, status);
            if (success) {
                return RequestUtils.buildResponse("更新状态成功", 200);
            } else {
                throw new CustomException(500, "部分用户更新状态失败");
            }
        }catch (Exception e) {
            logger.error("批量更新状态时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "更新用户状态时发生异常");
        }
    }


    // 图书管理员部分
    /**
     * 创建一个新的图书管理员。
     *
     * @param bookAdmin 包含新管理员详细信息的 BookAdmin 对象
     * @return 包含创建结果的响应对象
     * @throws CustomException 如果用户名已存在或发生其他异常
     */
    @PostMapping("/bookAdmins/create")
    public Map<String, Object> createBookAdmin(@RequestBody BookAdmin bookAdmin) {
        try {
            if (adminService.bookAdminUsernameTaken(bookAdmin.getUsername())
                    && adminService.bookAdminEmailTaken(bookAdmin.getEmail())) {
                throw new CustomException(403, "用户名或邮箱已存在");
            } else {
                return RequestUtils.buildResponse(adminService.createBookAdmin(bookAdmin), 200);
            }
        } catch (CustomException e) {
            logger.error("创建图书管理员时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 批量删除图书管理员。
     *
     * @param params 请求体，包含 bookAdminIds 列表
     * @return 删除结果的响应对象
     * @throws CustomException 如果请求参数中缺少 bookAdminIds 或删除失败
     */
    @DeleteMapping("/bookAdmins/batch/delete")
    public Map<String, Object> batchDeleteBookAdmins(@RequestBody Map<String, Object> params) {
        try {
            if (!params.containsKey("bookAdminIds")) {
                throw new CustomException(400, "请求参数中缺少 bookAdminIds");
            }
            List<Long> bookAdminIds = RequestUtils.processIds(params.get("bookAdminIds"));
            boolean success = adminService.batchDeleteBookAdmin(bookAdminIds);

            if (success) {
                return RequestUtils.buildResponse("删除成功", 200);
            } else {
                throw new CustomException(500, "部分或全部用户删除失败");
            }
        } catch (IllegalArgumentException e) {
            throw new CustomException(400, e.getMessage());
        } catch (Exception e) {
            logger.error("删除图书管理员时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "删除用户时发生异常：" + e.getMessage());
        }
    }

    /**
     * 获取图书管理员列表。
     *
     * @param request 请求体，包含分页信息（page, size）和过滤条件（status, username, email, bookAdminName）
     * @return 包含图书管理员列表的响应对象
     * @throws CustomException 如果发生异常
     */
    @PostMapping("/bookAdmins/all")
    public Map<String, Object> getBookAdmins(@RequestBody Map<String, Object> request) {
        try {
            int page = (int) request.getOrDefault("page", 0);
            int size = (int) request.getOrDefault("size", 10);
            Integer status = (Integer) request.get("status");
            String username = (String) request.get("username");
            String email = (String) request.get("email");
            String bookAdminName = (String) request.get("bookAdminName");
            Page<BookAdmin> bookAdmins = adminService.getAllBookAdmins(page, size, status, username, email, bookAdminName);
            return RequestUtils.buildResponse(bookAdmins, 200);
        } catch (Exception e) {
            logger.error("获取图书管理员列表时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "服务器内部错误");
        }
    }

    /**
     * 更新指定 ID 的图书管理员信息。
     *
     * @param id           图书管理员的 ID
     * @param bookAdminDetails 包含更新信息的 BookAdmin 对象
     * @return 包含更新结果的响应对象
     * @throws CustomException 如果发生异常
     */
    @PutMapping("/bookAdmins/update/{id}")
    public Map<String, Object> updateBookAdmin(@PathVariable Long id, @RequestBody BookAdmin bookAdminDetails) {
        try {
            Optional<BookAdmin> updatedBookAdmin = adminService.updateBookAdmin(id, bookAdminDetails);
            return RequestUtils.buildResponse(updatedBookAdmin, 200);
        } catch (Exception e) {
            logger.error("更新图书管理员时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "服务器内部错误");
        }
    }

    /**
     * 批量更新图书管理员的状态。
     *
     * @param request 请求体，包含 bookAdminIds 列表和 status
     * @return 更新状态结果的响应对象
     * @throws CustomException 如果请求参数中缺少 bookAdminIds 或 status，或更新失败
     */
    @PutMapping("/bookAdmins/batch/status")
    public Map<String, Object> batchUpdateStatus(@RequestBody Map<String, Object> request) {
        try {
            List<Long> bookAdminIds = RequestUtils.processIds(request.get("bookAdminIds"));
            Integer status = (Integer) request.get("status");
            boolean success = adminService.batchUpdateBookAdminStatus(bookAdminIds, status);
            if (success) {
                return RequestUtils.buildResponse("更新状态成功", 200);
            } else {
                throw new CustomException(500, "部分用户更新状态失败");
            }
        } catch (Exception e) {
            logger.error("批量更新状态时发生异常: {}", e.getMessage(), e);
            throw new CustomException(500, "更新用户状态时发生异常");
        }
    }
}

